@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>修改客户订单</title>
    <link href="~/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
    <script src="~/scripts/jquery-3.4.1.min.js"></script>
    <script src="~/scripts/layui-v2.5.6/layui/layui.js"></script>
    <style>
        body {
            padding: 15px;
            background: #f5f5f5;
        }
        .form-container {
            background: #fff;
            padding: 25px;
            border-radius: 4px;
            box-shadow: 0 1px 2px rgba(0,0,0,.1);
            max-width: 1400px;
            margin: 0 auto;
        }
        .layui-form-label {
            width: 80px;
            text-align: right;
            padding-right: 8px;
            font-size: 13px;
        }
        .layui-input-block {
            margin-left: 88px;
        }
        .required {
            color: #FF5722;
        }
        .form-buttons {
            text-align: center;
            margin-top: 25px;
            padding-top: 20px;
            border-top: 1px solid #e6e6e6;
        }
        .form-buttons .layui-btn {
            margin: 0 10px;
            min-width: 80px;
        }
        .layui-textarea {
            resize: vertical;
        }
        .quantity-container {
            display: flex;
            align-items: center;
        }
        .quantity-input {
            flex: 1;
        }
        .quantity-controls {
            display: flex;
            flex-direction: column;
            margin-right: 10px;
        }
        .quantity-btn {
            width: 30px;
            height: 19px;
            line-height: 17px;
            font-size: 12px;
            padding: 0;
            margin: 1px 0;
        }
        .search-btn {
            width: 40px;
            height: 38px;
            line-height: 38px;
            padding: 0;
            margin-left: 5px;
        }
        .section-title {
            font-size: 16px;
            font-weight: bold;
            color: #333;
            margin: 25px 0 15px 0;
            padding-bottom: 10px;
            border-bottom: 2px solid #009688;
        }
        .material-table-container {
            background: #fff;
            padding: 20px;
            border-radius: 4px;
            box-shadow: 0 1px 2px rgba(0,0,0,.1);
            margin-top: 20px;
        }
        .material-toolbar {
            margin-bottom: 15px;
        }
        .layui-table-cell {
            height: auto !important;
        }
        .disabled-input {
            background-color: #f5f5f5 !important;
            cursor: not-allowed !important;
        }
        .add-material-btn {
            padding: 2px 6px !important;
            font-size: 12px !important;
            height: 22px !important;
            line-height: 18px !important;
        }
        .add-material-btn:hover {
            background-color: #009688 !important;
            color: white !important;
        }
        .level-title-row {
            background-color: #f8f9fa !important;
        }
        .level-title-text {
            font-weight: bold;
            color: #009688;
            font-size: 14px;
        }
    </style>
</head>
<body>
    <div class="form-container">
        <form class="layui-form" lay-filter="editForm" id="editForm">
            <input type="hidden" name="orderId" id="orderId" />
            
            <!-- 第一行：产品信息 -->
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span class="required">*</span> 产品编号</label>
                        <div class="layui-input-block">
                            <div style="display: flex;">
                                <input type="text" name="productCode" placeholder="点击选择产品" class="layui-input" lay-verify="required" readonly>
                                <button type="button" class="layui-btn layui-btn-primary search-btn" id="selectProduct">
                                    <i class="layui-icon layui-icon-search"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span class="required">*</span> 产品名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="productName" placeholder="自动填充" class="layui-input" lay-verify="required" readonly>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 第二行：产品规格 -->
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md12">
                    <div class="layui-form-item">
                        <label class="layui-form-label">产品规格</label>
                        <div class="layui-input-block">
                            <input type="text" name="productSpec" placeholder="自动填充" class="layui-input" readonly>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 第三行：订单和客户编码 -->
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span class="required">*</span> 订单编码</label>
                        <div class="layui-input-block">
                            <input type="text" name="orderCode" placeholder="订单编码（不可修改）" class="layui-input disabled-input" lay-verify="required" readonly disabled>
                        </div>
                    </div>
                </div>
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">客户编码</label>
                        <div class="layui-input-block">
                            <div style="display: flex;">
                                <input type="text" name="customerCode" placeholder="点击选择客户" class="layui-input" readonly>
                                <button type="button" class="layui-btn layui-btn-primary search-btn" id="selectCustomer">
                                    <i class="layui-icon layui-icon-search"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 第四行：客户名称 -->
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md12">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span class="required">*</span> 客户名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="customerName" placeholder="自动填充" class="layui-input" lay-verify="required" readonly>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 第五行：日期信息 -->
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span class="required">*</span> 订货日期</label>
                        <div class="layui-input-block">
                            <input type="text" name="orderDate" placeholder="请选择订货日期" class="layui-input" lay-verify="required" id="orderDate">
                        </div>
                    </div>
                </div>
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span class="required">*</span> 交货日期</label>
                        <div class="layui-input-block">
                            <input type="text" name="deliveryDate" placeholder="请选择交货日期" class="layui-input" lay-verify="required" id="deliveryDate">
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 第六行：数量和单位 -->
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span class="required">*</span> 订货数量</label>
                        <div class="layui-input-block">
                            <div class="quantity-container">
                                <div class="quantity-controls">
                                    <button type="button" class="layui-btn layui-btn-primary quantity-btn" id="increaseBtn">+</button>
                                    <button type="button" class="layui-btn layui-btn-primary quantity-btn" id="decreaseBtn">-</button>
                                </div>
                                <input type="number" name="orderQuantity" value="1" class="layui-input quantity-input" lay-verify="required|number" min="1">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span class="required">*</span> 单位</label>
                        <div class="layui-input-block">
                            <select name="unit" lay-verify="required">
                                <option value="">请选择</option>
                                <option value="个">个</option>
                                <option value="公斤">公斤</option>
                                <option value="克">克</option>
                                <option value="吨">吨</option>
                                <option value="米">米</option>
                                <option value="件">件</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 第七行：规格型号和质量要求 -->
            <div class="layui-row layui-col-space15">
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">规格型号</label>
                        <div class="layui-input-block">
                            <input type="text" name="specModel" placeholder="请输入规格型号" class="layui-input">
                        </div>
                    </div>
                </div>
                <div class="layui-col-md6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">质量要求</label>
                        <div class="layui-input-block">
                            <textarea name="qualityRequirements" placeholder="请输入质量要求" class="layui-textarea" rows="3"></textarea>
                        </div>
                    </div>
                </div>
            </div>
        </form>

        <!-- 物料需求部分 -->
        <div class="material-table-container">
            <div class="section-title">物料需求</div>
            
            <!-- 工具栏 -->
            <div class="material-toolbar">
                <button type="button" class="layui-btn layui-btn-sm" id="addMaterialBtn">
                    <i class="layui-icon layui-icon-add-1"></i> 新增物料
                </button>
                <button type="button" class="layui-btn layui-btn-sm layui-btn-danger" id="deleteMaterialBtn">
                    <i class="layui-icon layui-icon-delete"></i> 删除选中
                </button>
            </div>

            <!-- 物料需求表格 -->
            <table class="layui-hide" id="materialTable" lay-filter="materialTable"></table>
        </div>

        <!-- 按钮区域 -->
        <div class="form-buttons">
            <button type="submit" class="layui-btn" lay-submit lay-filter="confirmBtn">确定</button>
            <button type="button" class="layui-btn layui-btn-normal" id="generateProductionBtn">生成生产工单</button>
            <button type="button" class="layui-btn layui-btn-primary" id="cancelBtn">取消</button>
        </div>
    </div>



    <script>
        layui.use(['form', 'laydate', 'layer', 'table'], function() {
            var form = layui.form;
            var laydate = layui.laydate;
            var layer = layui.layer;
            var table = layui.table;

            // 从URL参数获取订单ID
            function getUrlParameter(name) {
                try {
                    var url = new URL(window.location.href);
                    return url.searchParams.get(name);
                } catch (e) {
                    // 兼容性处理
                    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
                    var results = regex.exec(window.location.href);
                    if (!results) return null;
                    if (!results[2]) return '';
                    return decodeURIComponent(results[2].replace(/\+/g, ' '));
                }
            }

            var orderId = getUrlParameter('id');
            
            if (orderId) {
                $('#orderId').val(orderId);
                
                // 延迟加载订单数据，确保页面完全初始化
                setTimeout(function() {
                    loadOrderData(orderId);
                }, 500);
            } else {
                layer.msg('未获取到订单ID，无法加载数据', {icon: 2, time: 4000});
                
                // 初始化默认物料数据，避免表格为空
                materialRequirementsData = [
                    {
                        id: 1,
                        parentId: 0,
                        level: 1,
                        isLevelTitle: true,
                        levelTitle: '第一层',
                        materialCode: '',
                        materialName: '',
                        requiredQuantity: '',
                        inventoryQuantity: '',
                        unit: ''
                    }
                ];
                
                // 重新渲染物料表格
                table.reload('materialTable', {
                    data: materialRequirementsData
                });
            }

            // 初始化日期选择器
            laydate.render({
                elem: '#orderDate',
                type: 'date'
            });

            laydate.render({
                elem: '#deliveryDate',
                type: 'date'
            });

            // 物料需求数据
            var materialRequirementsData = [];
            var currentLevelCount = 0;

            // 初始化物料需求表格
            var materialTableIns = table.render({
                elem: '#materialTable',
                data: materialRequirementsData,

                cols: [[ 
                    {type: 'checkbox', fixed: 'left'},
                    {field: 'level', title: '层级/操作', width: 150, sort: true, templet: function(d) {
                        if (d.isLevelTitle) {
                            var addBtn = '<button type="button" class="layui-btn layui-btn-xs layui-btn-primary add-material-btn" data-id="' + d.id + '" style="margin-right: 5px;">' +
                                        '<i class="layui-icon layui-icon-add-1"></i>' +
                                        '</button>';
                            return addBtn + '<span class="level-title-text">' + d.levelTitle + '</span>';
                        }
                        return '';
                    }},
                    {field: 'materialCode', title: '物料编码', width: 150, templet: function(d) {
                        if (d.isLevelTitle) {
                            return '';
                        }
                        var indent = '';
                        for (var i = 1; i < d.level; i++) {
                            indent += '&nbsp;&nbsp;&nbsp;&nbsp;';
                        }
                        return indent + (d.materialCode || '');
                    }},
                    {field: 'materialName', title: '物料名称', width: 200, edit: 'text', templet: function(d) {
                        return d.isLevelTitle ? '' : (d.materialName || '');
                    }},
                    {field: 'requiredQuantity', title: '需求数量', width: 120, edit: 'text', templet: function(d) {
                        return d.isLevelTitle ? '' : (d.requiredQuantity || '');
                    }},
                    {field: 'inventoryQuantity', title: '库存量', width: 120, templet: function(d) {
                        return d.isLevelTitle ? '' : (d.inventoryQuantity || '');
                    }},
                    {field: 'unit', title: '单位', width: 80, edit: 'text', templet: function(d) {
                        return d.isLevelTitle ? '' : (d.unit || '');
                    }},
                    {title: '操作', width: 150, templet: function(d) {
                        if (d.isLevelTitle) {
                            return '';
                        }
                        return '<a class="layui-btn layui-btn-xs" lay-event="edit">' +
                               '<i class="layui-icon layui-icon-edit"></i> 编辑' +
                               '</a>' +
                               '<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">' +
                               '<i class="layui-icon layui-icon-delete"></i> 删除' +
                               '</a>';
                    }, fixed: 'right', align: 'center'}
                ]],
                skin: 'line',
                even: true,
                page: false,
                height: 300
            });

            // 数量增减按钮事件
            $('#increaseBtn').on('click', function() {
                var input = $('input[name="orderQuantity"]');
                var currentVal = parseInt(input.val()) || 1;
                input.val(currentVal + 1);
            });

            $('#decreaseBtn').on('click', function() {
                var input = $('input[name="orderQuantity"]');
                var currentVal = parseInt(input.val()) || 1;
                if (currentVal > 1) {
                    input.val(currentVal - 1);
                }
            });

            // 产品选择按钮事件
            $('#selectProduct').on('click', function() {
                layer.open({
                    type: 2,
                    title: '产品选择',
                    area: ['900px', '650px'],
                    content: '/CustomerOrder/ProductInfoDilog',
                    maxmin: true,
                    success: function(layero, index) {
                        window.productSelectCallback = function(productData) {
                            $('input[name="productCode"]').val(productData.code);
                            $('input[name="productName"]').val(productData.name);
                            $('input[name="productSpec"]').val(productData.spec);
                            layer.close(index);
                            layer.msg('产品选择成功');
                        };
                    },
                    end: function() {
                        window.productSelectCallback = null;
                    }
                });
            });

            // 客户选择按钮事件
            $('#selectCustomer').on('click', function() {
                layer.open({
                    type: 2,
                    title: '客户选择',
                    area: ['1100px', '700px'],
                    content: '/CustomerOrder/CustomerShowDilog',
                    maxmin: true,
                    success: function(layero, index) {
                        window.customerSelectCallback = function(customerData) {
                            $('input[name="customerCode"]').val(customerData.code);
                            $('input[name="customerName"]').val(customerData.name);
                            layer.close(index);
                            layer.msg('客户选择成功');
                        };
                    },
                    end: function() {
                        window.customerSelectCallback = null;
                    }
                });
            });


            
            // 新增物料按钮
            $('#addMaterialBtn').on('click', function() {
                currentLevelCount++;
                
                // 创建新的层级标题
                var newId = materialRequirementsData.length > 0 ? Math.max.apply(Math, materialRequirementsData.map(function(item) { return item.id || 0; })) + 1 : 1;
                
                var newLevelTitle = {
                    id: newId,
                    parentId: 0,
                    level: 1,
                    isLevelTitle: true,
                    levelTitle: '第' + getChineseNumber(currentLevelCount) + '层',
                    materialCode: '',
                    materialName: '',
                    requiredQuantity: '',
                    inventoryQuantity: '',
                    unit: ''
                };
                
                materialRequirementsData.push(newLevelTitle);
                
                // 重新渲染表格
                table.reload('materialTable', {
                    data: materialRequirementsData
                });
                
                layer.msg('已添加' + newLevelTitle.levelTitle);
            });
            


            // 数字转中文
            function getChineseNumber(num) {
                var chineseNums = ['', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十'];
                if (num <= 10) {
                    return chineseNums[num];
                } else {
                    return num.toString();
                }
            }

            // 删除选中物料
            $('#deleteMaterialBtn').on('click', function() {
                var checkStatus = table.checkStatus('materialTable');
                if (checkStatus.data.length === 0) {
                    layer.msg('请选择要删除的物料');
                    return;
                }
                
                var itemsToDelete = checkStatus.data.filter(function(item) {
                    return !item.isLevelTitle;
                });
                
                if (itemsToDelete.length === 0) {
                    layer.msg('不能删除层级标题，请选择具体的物料进行删除');
                    return;
                }
                
                layer.confirm('确定删除选中的 ' + itemsToDelete.length + ' 条物料记录吗？', function(index) {
                    itemsToDelete.forEach(function(item) {
                        for (var i = materialRequirementsData.length - 1; i >= 0; i--) {
                            if (materialRequirementsData[i].id === item.id) {
                                materialRequirementsData.splice(i, 1);
                                break;
                            }
                        }
                    });
                    
                    // 重新渲染表格
                    table.reload('materialTable', {
                        data: materialRequirementsData
                    });
                    layer.close(index);
                    layer.msg('删除成功');
                });
            });

            // 添加物料按钮点击事件（使用事件委托）
            $(document).on('click', '.add-material-btn', function() {
                var parentId = $(this).data('id');
                
                // 打开物料选择弹窗
                layer.open({
                    type: 2,
                    title: '物料选择',
                    area: ['1200px', '700px'],
                    content: '/CustomerOrder/MaterialSelectDialog',
                    maxmin: true,
                    success: function(layero, index) {
                        // 设置回调函数，供子页面调用
                        window.materialSelectCallback = function(materialData) {
                            // 找到父级项目
                            var parentIndex = -1;
                            for (var i = 0; i < materialRequirementsData.length; i++) {
                                if (materialRequirementsData[i].id === parentId) {
                                    parentIndex = i;
                                    break;
                                }
                            }
                            
                            if (parentIndex === -1) {
                                layer.msg('未找到父级层级', {icon: 2});
                                return;
                            }
                            
                            // 创建新的物料
                            var newId = materialRequirementsData.length > 0 ? Math.max.apply(Math, materialRequirementsData.map(function(item) { return item.id || 0; })) + 1 : 1;
                            
                            var newMaterial = {
                                id: newId,
                                parentId: parentId,
                                level: materialRequirementsData[parentIndex].level + 1,
                                levelTitle: '',
                                isLevelTitle: false,
                                materialCode: materialData.code,
                                materialName: materialData.name,
                                requiredQuantity: 1,
                                inventoryQuantity: 0,
                                unit: materialData.unit
                            };
                            
                            // 将新物料插入到父级项目后面
                            materialRequirementsData.splice(parentIndex + 1, 0, newMaterial);
                            
                            // 重新渲染表格
                            table.reload('materialTable', {
                                data: materialRequirementsData
                            });
                            
                            // 关闭弹窗
                            layer.close(index);
                            layer.msg('物料添加成功');
                        };
                    },
                    end: function() {
                        // 清理回调函数
                        window.materialSelectCallback = null;
                    }
                });
            });



            // 物料表格行工具事件
            table.on('tool(materialTable)', function(obj) {
                var data = obj.data;
                
                if (data.isLevelTitle) {
                    return;
                }
                
                if (obj.event === 'edit') {
                    layer.msg('编辑物料：' + data.materialName);
                } else if (obj.event === 'delete') {
                    layer.confirm('确定删除物料 "' + data.materialName + '" 吗？', function(index) {
                        for (var i = materialRequirementsData.length - 1; i >= 0; i--) {
                            if (materialRequirementsData[i].id === data.id) {
                                materialRequirementsData.splice(i, 1);
                                break;
                            }
                        }
                        
                        // 重新渲染表格
                        table.reload('materialTable', {
                            data: materialRequirementsData
                        });
                        
                        layer.close(index);
                        layer.msg('删除成功');
                    });
                }
            });



            // 表单提交
            form.on('submit(confirmBtn)', function(data) {
                var formData = data.field;
                
                // 如果layui表单数据获取失败，手动获取表单数据
                if (!formData.productCode || !formData.productName || !formData.customerName) {
                    formData = {
                        productCode: $('input[name="productCode"]').val(),
                        productName: $('input[name="productName"]').val(),
                        productSpec: $('input[name="productSpec"]').val(),
                        orderCode: $('input[name="orderCode"]').val(),
                        customerCode: $('input[name="customerCode"]').val(),
                        customerName: $('input[name="customerName"]').val(),
                        orderDate: $('input[name="orderDate"]').val(),
                        deliveryDate: $('input[name="deliveryDate"]').val(),
                        orderQuantity: $('input[name="orderQuantity"]').val(),
                        unit: $('select[name="unit"]').val(),
                        specModel: $('input[name="specModel"]').val(),
                        qualityRequirements: $('textarea[name="qualityRequirements"]').val()
                    };
                }
                
                var missingFields = [];
                if (!formData.productCode) missingFields.push('产品编号');
                if (!formData.productName) missingFields.push('产品名称');
                if (!formData.customerName) missingFields.push('客户名称');
                if (!formData.orderDate) missingFields.push('订货日期');
                if (!formData.deliveryDate) missingFields.push('交货日期');
                if (!formData.unit) missingFields.push('单位');
                
                if (missingFields.length > 0) {
                    layer.msg('请填写以下必填字段: ' + missingFields.join('、'), {icon: 2, time: 3000});
                    return false;
                }
                
                layer.msg('正在保存修改...', {
                    icon: 16,
                    time: 2000
                });
                
                // 构建订单信息
                var orderInfo = {
                    id: parseInt($('#orderId').val()),
                    productCode: String(formData.productCode || ''),
                    productName: String(formData.productName || ''),
                    productSpec: String(formData.productSpec || ''),
                    orderCode: String(formData.orderCode || ''),
                    customerCode: String(formData.customerCode || ''),
                    customerName: String(formData.customerName || ''),
                    orderDate: formData.orderDate ? new Date(formData.orderDate).toISOString() : new Date().toISOString(),
                    deliveryDate: formData.deliveryDate ? new Date(formData.deliveryDate).toISOString() : new Date().toISOString(),
                    orderQuantity: Math.max(1, parseInt(formData.orderQuantity) || 1),
                    unit: String(formData.unit || ''),
                    specModel: String(formData.specModel || ''),
                    qualityRequirements: String(formData.qualityRequirements || ''),
                    orderStatus: parseInt(0)
                };

                // 构建物料需求数据
                var materialRequirements = materialRequirementsData.map(function(item, index) {
                    // 确保parentId在Int32范围内
                    var parentId = parseInt(item.parentId) || 0;
                    if (parentId > 2147483647) {
                        parentId = 0;
                    }
                    
                    return {
                        customerOrderId: parseInt(orderInfo.id),
                        parentId: parentId,
                        level: parseInt(item.level) || 1,
                        isLevelTitle: Boolean(item.isLevelTitle),
                        levelTitle: String(item.levelTitle || ''),
                        materialCode: String(item.materialCode || ''),
                        materialName: String(item.materialName || ''),
                        specifications: String(item.specifications || ''),
                        requiredQuantity: Math.max(0, parseFloat(item.requiredQuantity) || 0),
                        inventoryQuantity: Math.max(0, parseFloat(item.inventoryQuantity) || 0),
                        unit: String(item.unit || ''),
                        remark: String(item.remark || ''),
                        sortOrder: parseInt(index),
                        createUser: 'system'
                    };
                });

                // 构建提交数据
                var submitData = {
                    orderInfo: orderInfo,
                    materialRequirements: materialRequirements
                };
                
                // 调用后端带事务的更新API
                $.ajax({
                    url: '/CustomerOrder/UpdateCustomerOrderWithMaterialRequirements',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(submitData),
                    success: function(response) {
                        if (response && (response.Success || response.success)) {
                            layer.msg('订单和物料需求修改成功！', {
                                icon: 1,
                                time: 2000
                            }, function() {
                                // 关闭弹窗并刷新父页面
                                var index = parent.layer.getFrameIndex(window.name);
                                parent.layer.close(index);
                            });
                        } else {
                            var errorMsg = (response && (response.Message || response.message)) ? (response.Message || response.message) : '修改失败';
                            layer.msg(errorMsg, {
                                icon: 2,
                                time: 3000
                            });
                        }
                    },
                    error: function(xhr, status, error) {
                        var errorMsg = '网络错误，请稍后重试';
                        if (xhr.responseText) {
                            try {
                                var errorResponse = JSON.parse(xhr.responseText);
                                errorMsg = errorResponse.Message || errorMsg;
                            } catch (e) {
                                errorMsg = xhr.responseText;
                            }
                        }
                        layer.msg(errorMsg, {
                            icon: 2,
                            time: 3000
                        });
                    }
                });

                return false;
            });

            // 生成生产工单按钮
            $('#generateProductionBtn').on('click', function() {
                layer.confirm('确定要生成生产工单吗？', {
                    icon: 3,
                    title: '提示'
                }, function(index) {
                    layer.msg('正在生成生产工单...', {
                        icon: 16,
                        time: 2000
                    });

                    setTimeout(function() {
                        layer.msg('生产工单生成成功！', {
                            icon: 1,
                            time: 1500
                        });
                    }, 2000);
                    
                    layer.close(index);
                });
            });

            // 取消按钮
            $('#cancelBtn').on('click', function() {
                layer.confirm('确定要取消吗？未保存的修改将丢失。', {
                    icon: 3,
                    title: '提示'
                }, function(index) {
                    var frameIndex = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(frameIndex);
                    layer.close(index);
                });
            });

            // 加载订单数据的函数
            function loadOrderData(orderId) {
                var loadingIndex = layer.msg('正在加载订单数据...', {
                    icon: 16, 
                    time: 0,
                    shade: 0.1
                });
                
                $.ajax({
                    url: '/CustomerOrder/GetCustomerOrderById',
                    type: 'GET',
                    data: { id: orderId },
                    timeout: 10000,
                    success: function(response) {
                        layer.close(loadingIndex);
                        
                        var isSuccess = response && (response.Success || response.success);
                        var data = response && (response.Data || response.data);
                        
                        if (isSuccess && data) {
                            // 填充表单数据
                            $('input[name="productCode"]').val(data.productCode || '');
                            $('input[name="productName"]').val(data.productName || '');
                            $('input[name="productSpec"]').val(data.productSpec || '');
                            $('input[name="orderCode"]').val(data.orderNumber || '');
                            $('input[name="customerCode"]').val(data.customerCode || '');
                            $('input[name="customerName"]').val(data.customerName || '');
                            $('input[name="orderDate"]').val(formatDate(data.orderDate));
                            $('input[name="deliveryDate"]').val(formatDate(data.deliveryDate));
                            $('input[name="orderQuantity"]').val(data.orderQuantity || 1);
                            $('select[name="unit"]').val(data.unit || '');
                            $('input[name="specModel"]').val(data.specificationModel || '');
                            $('textarea[name="qualityRequirements"]').val(data.qualityRequirement || '');
                            
                            // 重新渲染表单
                            form.render();
                            
                            // 加载物料需求数据
                            loadMaterialRequirements(orderId);
                            
                            layer.msg('订单数据加载完成', {icon: 1, time: 1500});
                        } else {
                            var errorMsg = response && (response.Message || response.message) ? (response.Message || response.message) : '加载订单数据失败';
                            layer.msg(errorMsg, {icon: 2, time: 3000});
                        }
                    },
                    error: function(xhr, status, error) {
                        layer.close(loadingIndex);
                        
                        var errorMsg = '网络错误，加载订单数据失败';
                        if (status === 'timeout') {
                            errorMsg = '请求超时，请检查网络连接';
                        } else if (xhr.status === 404) {
                            errorMsg = '订单数据接口不存在';
                        } else if (xhr.status === 500) {
                            errorMsg = '服务器内部错误';
                        }
                        
                        layer.msg(errorMsg, {icon: 2, time: 3000});
                    }
                });
            }

            // 加载物料需求数据的函数
            function loadMaterialRequirements(orderId) {
                $.ajax({
                    url: '/CustomerOrder/GetMaterialRequirementsByOrderId',
                    type: 'GET',
                    data: { customerOrderId: orderId },
                    success: function(response) {
                        var isSuccess = response && (response.Success || response.success);
                        var data = response && (response.Data || response.data);
                        
                        if (isSuccess && data && data.length > 0) {
                            // 将后端数据转换为前端表格格式
                            materialRequirementsData = data.map(function(item) {
                                return {
                                    id: item.id || item.Id,
                                    parentId: item.parentId || item.ParentId,
                                    level: item.level || item.Level,
                                    isLevelTitle: item.isLevelTitle || item.IsLevelTitle,
                                    levelTitle: item.levelTitle || item.LevelTitle || '',
                                    materialCode: item.materialCode || item.MaterialCode || '',
                                    materialName: item.materialName || item.MaterialName || '',
                                    specifications: item.specifications || item.Specifications || '',
                                    requiredQuantity: item.requiredQuantity || item.RequiredQuantity || '',
                                    inventoryQuantity: item.inventoryQuantity || item.InventoryQuantity || '',
                                    unit: item.unit || item.Unit || '',
                                    remark: item.remark || item.Remark || '',
                                    sortOrder: item.sortOrder || item.SortOrder || 0
                                };
                            });
                        } else {
                            // 如果没有数据，使用默认的空层级
                            materialRequirementsData = [
                                {
                                    id: 1,
                                    parentId: 0,
                                    level: 1,
                                    isLevelTitle: true,
                                    levelTitle: '第一层',
                                    materialCode: '',
                                    materialName: '',
                                    requiredQuantity: '',
                                    inventoryQuantity: '',
                                    unit: ''
                                }
                            ];
                        }
                        
                        // 重新渲染物料表格
                        table.reload('materialTable', {
                            data: materialRequirementsData
                        });
                    },
                    error: function(xhr, status, error) {
                        // 使用默认数据
                        materialRequirementsData = [
                            {
                                id: 1,
                                parentId: 0,
                                level: 1,
                                isLevelTitle: true,
                                levelTitle: '第一层',
                                materialCode: '',
                                materialName: '',
                                requiredQuantity: '',
                                inventoryQuantity: '',
                                unit: ''
                            }
                        ];
                        
                        // 重新渲染物料表格
                        table.reload('materialTable', {
                            data: materialRequirementsData
                        });
                        
                        layer.msg('物料需求数据加载失败', {icon: 2, time: 2000});
                    }
                });
            }

            // 日期格式化函数
            function formatDate(dateString) {
                if (!dateString) return '';
                var date = new Date(dateString);
                var year = date.getFullYear();
                var month = String(date.getMonth() + 1).padStart(2, '0');
                var day = String(date.getDate()).padStart(2, '0');
                return year + '-' + month + '-' + day;
            }

            // 渲染表单
            form.render();
            

        });
    </script>
</body>
</html> 